package blf.librarysystem.Controller;

import blf.librarysystem.Dao.BookMapper;
import blf.librarysystem.Pojo.Book;
import blf.librarysystem.Service.BookService;
import blf.librarysystem.Utils.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class BookController {

    @Resource
    private BookService bookService;
    @Autowired
    private BookMapper bookMapper;

    @GetMapping("/book")
    public String list() {
        return "admin/book-list";
    }

    @GetMapping("/book/listall")
    @ResponseBody
    public Result<Book> listall(@RequestParam Map<String, Object> params) {
        int page = Integer.parseInt(params.get("page").toString());
        int limit = Integer.parseInt(params.get("limit").toString());
        int start = (page - 1) * limit;
        return bookService.findBookList(start, limit);
    }

    @GetMapping("/book/listbykeys")
    @ResponseBody
    public Result<Book> listByKeys(@RequestParam("readerName") String readerName, @RequestParam("bookName") String bookName, @RequestParam("borrowStatus") String borrowStatus, @RequestParam Map<String, Object> params) throws ParseException {
        int page = Integer.parseInt(params.get("page").toString());
        int limit = Integer.parseInt(params.get("limit").toString());
        int start = (page - 1) * limit;
//        DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Timestamp borrowtime = new Timestamp(dateTimeFormat.parse(borrow_time).getTime());
//        Timestamp returntime = new Timestamp(dateTimeFormat.parse(borrow_time).getTime());
        return bookService.listByKeys(readerName, bookName, borrowStatus, start, limit);
    }

    @GetMapping("/book/borrowBook")
    //required = false 前端如果没有传参的时候，会设置参数为null
    public String borrow(@RequestParam(required = false) Integer bookId, Model model) {
        Book book = bookMapper.selectByPrimaryKey(bookId);
        model.addAttribute("bookInfo", book);
        return "admin/book-borrow";
    }

    @PostMapping("/book/borrowBook")
    @ResponseBody
    public Result<Book> borrowBook(@RequestParam("bookId") int bookId, @RequestParam("borrowId") int borrowId) {
        return bookService.borrowBook(bookId, borrowId);
    }

    @PostMapping("/book/returnBook")
    @ResponseBody
    public Result<Book> returnBook(@RequestParam("bookId") int bookId) {
        return bookService.returnBook(bookId);
    }
}
